package com.apchernykh.rozhlasapp.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateUtil {

	public static final SimpleDateFormat mRfc822DateFormats[] = new SimpleDateFormat[] {
		new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US),
		new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US),
			new SimpleDateFormat("EEE, d MMM yy HH:mm z", Locale.US),
			new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US),
			new SimpleDateFormat("EEE, d MMM yyyy HH:mm z", Locale.US),
			new SimpleDateFormat("d MMM yy HH:mm z", Locale.US), 
			new SimpleDateFormat("d MMM yy HH:mm:ss z", Locale.US),
			new SimpleDateFormat("d MMM yyyy HH:mm z", Locale.US), 
			new SimpleDateFormat("d MMM yyyy HH:mm:ss z", Locale.US)
		};
	
	/**
	 * Parse an RFC 822 date string.
	 * 
	 * @param iDateString The date string to parse
	 * @return The date, or null if it could not be parsed.
	 */
	public static Date parseRfc822DateString(String iDateString) {
		Date aDate = null;
		for (SimpleDateFormat aDateFormat : mRfc822DateFormats) {
			try {
				aDate = aDateFormat.parse(iDateString);
			} catch (ParseException aParseException) {
				// Don't care, we'll just run through all
			}
			if (aDate != null) {
				return aDate;
			}
		}
		return aDate;
	}

	/**
	 * Format a date into a format suitable for SQLite
	 * 
	 * @param iDate The date to format
	 * @return The formatted date, or null if it could not be formatted.
	 */
	public static String dateToSqliteDateString(Date iDate) {
		// The format is the same as CURRENT_TIMESTAMP: "YYYY-MM-DD HH:MM:SS"
		SimpleDateFormat aDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
		if (iDate != null) {
			return aDateFormat.format(iDate);
		}
		return null;
	}
}
